package com.jwork.progress.controllers;

import com.jwork.progress.params.CommonResponse;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@RestController
@RequestMapping(value = "/sse")
public class SseEmitterController {
    private static final Map<String, SseEmitter> emitters = new ConcurrentHashMap<>();

    @GetMapping("/subscribe")
    public SseEmitter subscribe(@RequestParam String id) {
        SseEmitter sseEmitter = new SseEmitter();
        emitters.put(id, sseEmitter);
        sseEmitter.onCompletion(() -> emitters.remove(id));
        sseEmitter.onTimeout(() -> {
            emitters.remove(id);
        });
        return sseEmitter;
    }

    @PostMapping("/push/{id}")
    public CommonResponse push(@PathVariable String id, @RequestBody String msg) {
        SseEmitter sseEmitter = emitters.get(id);
        if (!ObjectUtils.isEmpty(sseEmitter)) {
            try {
                sseEmitter.send(msg);
            } catch (IOException e) {
                throw new RuntimeException(e);
            } finally {
                sseEmitter.complete();
                emitters.remove(id);
            }
        }
        return CommonResponse.success("成功！");
    }
}
